# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Mario Emmenlauer <memmenlauer@biodataanalysis.de>

_realname=ccache
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=4.5.1
pkgrel=1
pkgdesc="Compiler cache that speeds up recompilation by caching previous compilations (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://ccache.dev/"
license=("GPL3")
replaces=("${MINGW_PACKAGE_PREFIX}-${_realname}-git")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-asciidoctor"
             "${MINGW_PACKAGE_PREFIX}-pkg-config")
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-hiredis"
         "${MINGW_PACKAGE_PREFIX}-zstd")
options=('staticlibs' 'strip')
source=("https://github.com/ccache/ccache/releases/download/v${pkgver}/${_realname}-${pkgver}.tar.xz"{,.asc})
sha256sums=('51186ebe0326365f4e6131e1caa8911de7da4aa6718efc00680322d63a759517'
            'SKIP')
validpgpkeys=('5A939A71A46792CF57866A51996DDA075594ADB8') # Joel Rosdahl <joel@rosdahl.net>

build() {
  mkdir -p "${srcdir}"/build-${MINGW_CHOST} && cd "${srcdir}"/build-${MINGW_CHOST}

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  # Note: enabling static linking as default has brought a bug to light in mingw32
  #       "-DSTATIC_LINK=OFF" can be removed as soon as the bug is fixed
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    ${MINGW_PREFIX}/bin/cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -DSTATIC_LINK=OFF \
      ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .
}

check() {
  # run unittest to verify that the program is not broken
  cd "${srcdir}"/build-${MINGW_CHOST}
  ${MINGW_PREFIX}/bin/ctest -R unittest
}

package() {
  cd "${srcdir}/build-${MINGW_CHOST}"

  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --build . --target install

  # hack: use bash scripts as shortcuts since we cannot use symlinks
  install -d ${pkgdir}${MINGW_PREFIX}/lib/ccache/bin
  cd ${pkgdir}${MINGW_PREFIX}/lib/ccache/bin
  scripts=(c++ cc cpp gcc g++ ${MINGW_CHOST}-g++ ${MINGW_CHOST}-c++ ${MINGW_CHOST}-gcc)
  for fn in ${scripts[*]}; do
    echo -e '#!/bin/bash\n\nccache '${MINGW_PREFIX}'/bin/'$fn' "$@"' > $fn
  done
}
